package com.bxd.baodan.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.adapter.CommonAdapter;
import com.bxd.baodan.adapter.ViewHolder;
import com.bxd.baodan.app.Constant;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.item.AskInfoItem;
import com.bxd.baodan.item.GroupBean;
import com.bxd.baodan.item.QesTagBean;
import com.bxd.baodan.item.SortItem;
import com.bxd.baodan.util.AppManager;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.LogUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.StringUtil;
import com.bxd.baodan.widget.MyTextWatcher;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

/**
 * 想买保险,有疑问
 */
public class AskBuyActivity extends BaseActivity {
    List<SortItem> tagList = new ArrayList<>();
    List<SortItem> budgetList = new ArrayList<>();
    private HashSet<SortItem> tagSet = new HashSet<>();
    private String[] budgets = {"不限预算", "5000以内", "5000～1万", "1万～3万", "3万～6万", "6万以上"};

    ListView lv;

    MAdapter adapter;

    List<GroupBean> list = new ArrayList<>();
    String member = "";
    String currentAge, haveShebao, mBudget, insure_type, currentGender, otherQuestion;
    public String tid, qid;
    public String question_content = "";


    CommonAdapter budgetAdapter;
    private AskInfoItem askInfoItem;
    AskInfoItem.KeyBuyInsure keyBuyInsure;
    AskInfoItem.Sex sex;
    AskInfoItem.Doubt doubt;
    boolean isFinish;
    private boolean isFinishError;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ask);
        setActionBarTitle("想买保险,有疑问");


        askInfoItem = new AskInfoItem();
        keyBuyInsure = new AskInfoItem.KeyBuyInsure();

        doubt = new AskInfoItem.Doubt();
        askInfoItem.choice = 0 + "";
        askInfoItem.type = 0 + "";


        for (int i = 0; i < budgets.length; i++) {
            SortItem item = new SortItem();
            item.id = i + "";
            item.name = budgets[i];
            budgetList.add(item);
        }


        findViewById(R.id.bar_iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                showExitDialog("确认退出快速提问吗?");

            }
        });

        lv = (ListView) findViewById(R.id.lv);


        NetUtil netUtil = new NetUtil(this, JsonApi.QUESTION_OPTIONS);
        netUtil.postRequest("加载中", new NetUtil.RequestStringListener() {
            @Override
            public void onComplete(String result) {

                QesTagBean qesTagBean = new Gson().fromJson(result, QesTagBean.class);
                List<SortItem> tag = qesTagBean.data.list.tag;
                tagList.clear();
                if (tag != null) {
                    tagList.addAll(tag);
                    tid = tagList.get(0).tid;   // TODO: 2017/11/14 只有tag,用于传参数cateId
                }
            }
        });


        GroupBean first = new GroupBean();
        first.middleVisible = true;
        first.layout = R.layout.ask_item_member;
        list.add(first);


        adapter = new MAdapter(this, list);

        adapter.setListener(new OkListener() {
            @Override
            public void next(int position, GroupBean nextBean) {

                GroupBean current = list.get(position);
                if (position == 0) {
                    current.leftVisible = false;
                    current.rightVisible = false;
                } else {
                    current.leftVisible = true;
                    current.rightVisible = true;
                }

                current.middleVisible = false;

                nextBean.leftVisible = true;
                nextBean.rightVisible = true;
                nextBean.middleVisible = true;


                list.add(nextBean);
                adapter.notifyDataSetChanged();
                lv.smoothScrollToPosition(adapter.getCount());

            }


            @Override
            public void pre(int position) {
                list.get(position - 1).middleVisible = true;
                list.remove(position);
                adapter.notifyDataSetChanged();
                lv.setSelection(adapter.getCount());
            }
        });
        lv.setAdapter(adapter);
    }


    class MAdapter extends BaseAdapter {
        private List<GroupBean> list;
        private Context context;
        private OkListener listener;


        MAdapter(Context context, List<GroupBean> list) {
            this.list = list;
            this.context = context;
        }


        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int i) {
            return list.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {

            final ViewHolder holder;
            final GroupBean item = list.get(i);
            if (view == null) {
                view = View.inflate(AskBuyActivity.this, R.layout.ask_list_item, null);
                holder = new ViewHolder();
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            holder.left = (TextView) view.findViewById(R.id.left);
            holder.right = (TextView) view.findViewById(R.id.right);
            holder.middle = (LinearLayout) view.findViewById(R.id.middle);


            holder.left.setVisibility(item.leftVisible ? View.VISIBLE : View.GONE);
            holder.right.setVisibility(item.rightVisible ? View.VISIBLE : View.GONE);
            holder.middle.setVisibility(item.middleVisible ? View.VISIBLE : View.GONE);


            holder.left.setText(item.left);
            holder.right.setText(item.right);
            ViewGroup mid = (ViewGroup) View.inflate(context, item.layout, null);


            holder.middle.removeAllViews();
            holder.middle.addView(mid);

            if (item.middleVisible) {


                final String memberText = member.equals("自己") ? "" : member;
                if (item.layout == R.layout.ask_item_age) {
                    TextView textView = (TextView) mid.findViewById(R.id.title);
                    textView.setText("您" + memberText + "的年龄");
                } else if (item.layout == R.layout.ask_item_gender) {
                    TextView textView = (TextView) mid.findViewById(R.id.title);
                    textView.setText("您" + memberText + "的性别");
                } else if (item.layout == R.layout.ask_item_shebao) {
                    TextView textView = (TextView) mid.findViewById(R.id.title);
                    textView.setText("您" + memberText + "的社保情况");
                }


                try {
                    mid.findViewById(R.id.finish).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }


                switch (item.layout) {
                    case R.layout.ask_item_member:
                        parseMember(mid);

                        break;

                    case R.layout.ask_item_gender:
                        parseGender(mid);

                        break;

                    case R.layout.ask_item_age:
                        parseAge(mid);
                        break;

                    case R.layout.ask_item_shebao:
                        parseSheBao(mid);
                        break;
                    case R.layout.ask_insure_type:
                        parseInsureType(mid);
                        break;

                    case R.layout.ask_insure_budget:
                        parseBudget(mid);
                        break;
                    case R.layout.ask_item_other_question:
                        parseOtherQuestion(mid);
                        break;
                    case R.layout.ask_item_finish:
                        parseFinish(mid);
                        break;

                }


                mid.findViewById(R.id.next).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {


                        GroupBean nextBean = new GroupBean();
                        // String memberText = member.equals("自己") ? "" : member;

                        switch (item.layout) {


                            case R.layout.ask_item_member:
                                if (StringUtil.isEmpty(member)) {
                                    showToast("请完善信息");
                                    return;
                                }
                                if (member.equals("自己")) {
                                    nextBean.layout = R.layout.ask_item_gender;
                                } else {
                                    nextBean.layout = R.layout.ask_item_age;
                                }
                                nextBean.left = "您想给谁买保险";
                                nextBean.right = member;

                                break;


                            case R.layout.ask_item_gender:
                                if (StringUtil.isEmpty(currentGender)) {
                                    showToast("请完善信息");
                                    return;
                                }

                                nextBean.left = "您的性别";
                                nextBean.layout = R.layout.ask_item_age;
                                nextBean.right = currentGender;
                                break;

                            case R.layout.ask_item_age:
                                if (StringUtil.isEmpty(currentAge)) {
                                    showToast("请完善信息");
                                    return;
                                }
                                if (Integer.parseInt(currentAge) > 120) {
                                    showToast("年龄不能超过120岁");
                                    return;
                                }
                                nextBean.left = "您" + memberText + "的年龄";
                                nextBean.layout = R.layout.ask_item_shebao;
                                nextBean.right = currentAge + "岁";
                                break;

                            case R.layout.ask_item_shebao:
                                if (StringUtil.isEmpty(haveShebao)) {
                                    showToast("请完善信息");
                                    return;
                                }


                                nextBean.left = "您" + memberText + "的社保情况";
                                nextBean.layout = R.layout.ask_insure_type;
                                nextBean.right = haveShebao;
                                break;

                            case R.layout.ask_insure_type:
                                if (StringUtil.isEmpty(insure_type)) {
                                    showToast("请完善信息");
                                    return;
                                }
                                nextBean.left = "您想要买什么类型的保险";
                                nextBean.layout = R.layout.ask_insure_budget;
                                nextBean.right = insure_type;
                                break;

                            case R.layout.ask_insure_budget:
                                if (StringUtil.isEmpty(mBudget)) {
                                    showToast("请完善信息");
                                    return;
                                }
                                nextBean.left = "您的投保预算是多少";
                                nextBean.layout = R.layout.ask_item_other_question;
                                nextBean.right = mBudget;
                                break;


                            case R.layout.ask_item_other_question:
                                if (StringUtil.isEmpty(otherQuestion)) {
                                    showToast("请完善信息");
                                    return;
                                }
                                if (otherQuestion.length() < 5) {
                                    showToast("字数这么少，真的把想问的说清楚了吗？");
                                    return;
                                }
                                nextBean.left = "补充说明";
                                nextBean.right = otherQuestion;
                                nextBean.layout = R.layout.ask_item_finish;

                                break;

                        }


                        listener.next(i, nextBean);
                    }
                });

                try {
                    mid.findViewById(R.id.bar_iv_close).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            listener.pre(i);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            return view;
        }

        public void setListener(OkListener listener) {
            this.listener = listener;
        }

        class ViewHolder {
            TextView left;
            TextView right;
            LinearLayout middle;
        }


    }


    private void parseFinish(final ViewGroup mid) {


        final TextView et = (TextView) mid.findViewById(R.id.content);
        et.setText(question_content);
        mid.findViewById(R.id.open_question).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppManager.getInstance().finishOtherActivity(MainActivity.class);
             //   openActivity(AllQuestionActivity.class);
                openActivity(QuestionDetailActivity.class, new String[]{"qid"}, new String[]{qid});
                finish();
            }
        });
        if (isFinishError) {
            mid.setVisibility(View.GONE);
        }

        if (!(isFinish || isFinishError)) {
            NetUtil netUtil = new NetUtil(AskBuyActivity.this, JsonApi.QUESTION_ADDQUESTION);
            if (sex != null) {
                keyBuyInsure.sex = sex;
            }

            askInfoItem.keyOfBuyInsure = keyBuyInsure;

            final String json = new Gson().toJson(askInfoItem);

            LogUtil.e("想买保险提问json: " + json);

            netUtil.setParams("options", json);
            netUtil.setParams("cateId", tid);
            netUtil.postRequest("", new NetUtil.RequestStringListener() {
                @Override
                public void onComplete(String result) {
                    String data = JSONUtil.getData(result);
                    question_content = JSONUtil.getData("content", data);
                    et.setText(question_content);
                    qid = JSONUtil.getData("qid", data);
                    isFinish = true;
                }

                @Override
                public void onError(String result) {
                    if (JSONUtil.getCode(result) == 8000) {
                        //token过期
                        LoginInfo.getInstance(App.getContext()).cancelLogin(App.getContext());
                        App.getContext().sendBroadcast(new Intent(Constant.ACTION_LOGIN_LOGINOUT));
                    }
                    //为了把吐司显示时间长一些
                    Toast.makeText(App.getContext(), JSONUtil.getMessage(result), Toast.LENGTH_LONG).show();
                    mid.setVisibility(View.GONE);
                    isFinishError = true;
                }
            });
        }

    }

    private void parseOtherQuestion(ViewGroup mid) {

        if (sex != null) {
            keyBuyInsure.sex = sex;
        }
        askInfoItem.keyOfBuyInsure = keyBuyInsure;

        final String json = new Gson().toJson(askInfoItem);
        LogUtil.e("不完全json: " + json);


        final EditText et = (EditText) mid.findViewById(R.id.et_question);
        et.addTextChangedListener(new MyTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                otherQuestion = et.getText().toString();
                askInfoItem.supplement = otherQuestion;  // TODO: 2017/11/14 补充说明
            }
        });

    }

    private void parseGender(ViewGroup mid) {
        currentGender = "";
        sex = new AskInfoItem.Sex();
        RadioGroup genderRg = (RadioGroup) mid.findViewById(R.id.gender_rg);
        genderRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                currentGender = ((RadioButton) group.findViewById(checkedId)).getText().toString();
                if (checkedId == R.id.man) {
                    currentGender = "男";
                    sex.sex = 1 + "";   // TODO: 2017/11/14 性别
                } else if (checkedId == R.id.woman) {
                    currentGender = "女";
                    sex.sex = 2 + "";   // TODO: 2017/11/14 性别
                } else {
                    currentGender = "";
                }


            }
        });
    }


    private void parseInsureType(ViewGroup mid) {
        // TODO: 2017/11/13 多选 保险类型
        insure_type = "";
        tagSet.clear();
        GridView gv = (GridView) mid.findViewById(R.id.type_gv);
        gv.setAdapter(new CommonAdapter<SortItem>(AskBuyActivity.this, tagList, R.layout.ask_check_item) {
            @Override
            public void convert(ViewHolder holder, final SortItem item) {
                ((CheckBox) holder.getView(R.id.check)).setText(item.name);
                ((CheckBox) holder.getView(R.id.check)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (isChecked) {
                            tagSet.add(item);
                        } else {
                            try {
                                tagSet.remove(item);
                            } catch (Exception e) {

                            }
                        }

                        StringBuilder idBuilder = new StringBuilder();
                        StringBuilder strBuilder = new StringBuilder();

                        Iterator<SortItem> iterator = tagSet.iterator();
                        while (iterator.hasNext()) {
                            SortItem next = iterator.next();
                            idBuilder.append(next.id);
                            strBuilder.append(next.name);
                            if (iterator.hasNext()) {
                                idBuilder.append(",");
                                strBuilder.append(",");
                            }
                        }
                        insure_type = strBuilder.toString();
                        keyBuyInsure.insureType = idBuilder.toString();  // TODO: 2017/11/14 保险类型


                    }
                });


            }
        });
    }


    private void parseBudget(final ViewGroup mid) {

        //保险预算 ,单选
        mBudget = "";
        for (SortItem it :
                budgetList) {
            it.isChecked = false;
        }

        GridView gv = (GridView) mid.findViewById(R.id.type_gv);
        budgetAdapter = new CommonAdapter<SortItem>(AskBuyActivity.this, budgetList, R.layout.ask_check_item_noclick) {
            @Override
            public void convert(final ViewHolder holder, final SortItem item) {
                final CheckBox checkBox = (CheckBox) holder.getView(R.id.check);
                LinearLayout check_ly = (LinearLayout) holder.getView(R.id.check_ly);

                checkBox.setText(item.name);
                checkBox.setChecked(item.isChecked);


                check_ly.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        boolean check = !item.isChecked;
                        for (int i = 0; i < budgetList.size(); i++) {
                            if (i == holder.getPosition()) {
                                budgetList.get(i).isChecked = check;
                                if (check) {
                                    mBudget = budgetList.get(i).name;
                                    keyBuyInsure.budget = i + "";  // TODO: 2017/11/14 预算
                                } else {
                                    mBudget = "";
                                }
                            } else {
                                budgetList.get(i).isChecked = false;
                            }

                        }
                        budgetAdapter.notifyDataSetChanged();

                    }
                });


            }
        };
        gv.setAdapter(budgetAdapter);
    }


    private void parseAge(ViewGroup mid) {
        currentAge = "";
        final EditText et = ((EditText) mid.findViewById(R.id.age_et));
        et.addTextChangedListener(new MyTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                currentAge = et.getText().toString();
                keyBuyInsure.questionAskerBirthday = currentAge;  // TODO: 2017/11/14 年龄
            }
        });

    }


    final int[] lyIds = {R.id.my_ly, R.id.laogong_ly, R.id.lao_po_ly, R.id.father_ly, R.id.mather_ly, R.id.son_ly, R.id.girl_ly};
    final int[] imgIds = {R.id.my_check, R.id.laogong_check, R.id.laopo_check, R.id.father_check, R.id.mather_check, R.id.son_check, R.id.girl_check};

    final String[] names = {"自己", "丈夫", "妻子", "父亲", "母亲", "儿子", "女儿"};


    private void parseMember(final ViewGroup view) {

        member = "";
        sex = null; // TODO: 2017/11/14 不是自己的时候用不用传性别?
        for (int j = 0; j < lyIds.length; j++) {
            final int finalJ = j;
            view.findViewById(lyIds[j]).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    for (int i = 0; i < lyIds.length; i++) {
                        view.findViewById(imgIds[i]).setVisibility(i == finalJ ? View.VISIBLE : View.GONE);
                        if (i == finalJ) {
                            member = names[i];
                            keyBuyInsure.buyInsureForWhom = i + "";  // TODO: 2017/11/14 成员
                        }

                    }
                }
            });
        }


    }


    private void parseSheBao(ViewGroup mid) {
        haveShebao = "";

        RadioGroup rg_shebao = (RadioGroup) mid.findViewById(R.id.rg_shebao);
        rg_shebao.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                haveShebao = ((RadioButton) group.findViewById(checkedId)).getText().toString();


                if (checkedId == R.id.have) {
                    keyBuyInsure.haveSocialInsurence = "0";  // TODO: 2017/11/14 社保
                    haveShebao = "有社保";
                } else if (checkedId == R.id.no) {
                    haveShebao = "无社保";
                    keyBuyInsure.haveSocialInsurence = "1";
                }


            }
        });
    }


    interface OkListener {
        public void next(int position, GroupBean bean);

        public void pre(int position);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            showExitDialog("确认退出快速提问吗?");
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }


}
